# Copyright 2021-2023 @ Shenzhen Bay Laboratory &
#                       Peking University &
#                       Huawei Technologies Co., Ltd
#
# This code is a part of Cybertron package.
#
# The Cybertron is open-source software based on the AI-framework:
# PyTorch (https://pytorch.org/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""
Module for evaluation
"""

from typing import Union, List, Tuple, Optional
from numpy import ndarray

import torch
from torch import nn, Tensor

from ..utils import get_arguments, get_tensor
from .wrapper import MoleculeWrapper
from ..cybertron import Cybertron


class MolWithEvalCell(MoleculeWrapper):
    """Basic module to combine the network and the loss/evaluate function.

    Args:
        data_keys (List[str]): List of data keys specifying inputs and labels.
        network (Cybertron): Neural network of Cybertron.
        loss_fn (Union[nn.Module, List[nn.Module]], optional): Loss function(s). Defaults to None.
        loss_weights (Union[float, Tensor, ndarray, List], optional): Weights for loss functions. Defaults to 1.
        calc_force (bool, optional): Whether to calculate forces via automatic differentiation. Defaults to False.
        energy_key (str, optional): Key for energy data. Defaults to 'energy'.
        force_key (str, optional): Key for force data. Defaults to 'force'.
        weights_normalize (bool, optional): Whether to normalize loss weights. Defaults to True.
        normed_evaldata (bool, optional): Whether the evaluation data is normalized. Defaults to False.
    """
    def __init__(self,
                 data_keys: List[str],
                 network: Cybertron,
                 loss_fn: Union[nn.Module, List[nn.Module]] = None,
                 loss_weights: Union[float, Tensor, ndarray, List] = 1,
                 calc_force: bool = False,
                 energy_key: str = 'energy',
                 force_key: str = 'force',
                 weights_normalize: bool = True,
                 normed_evaldata: bool = False,
                 **kwargs
                 ):
        super().__init__(
            network=network,
            loss_fn=loss_fn,
            data_keys=data_keys,
            calc_force=calc_force,
            energy_key=energy_key,
            force_key=force_key,
            loss_weights=loss_weights,
            weights_normalize=weights_normalize,
        )
        self._kwargs = get_arguments(locals(), kwargs)

        self._normed_evaldata = normed_evaldata
        self._force_id = self.get_index(self.force_key, self.label_keys)

        if loss_fn is not None:
            self._loss_fn = self._check_loss(loss_fn)
            self._loss_weights = self._check_weights(loss_weights)
            self._molecular_loss = self._set_molecular_loss()
            self._any_atomwise = any(self._molecular_loss)
            self._set_atomwise()

        self.zero = torch.tensor(0, dtype=torch.float32, device=self.device)

    def print_info(self, num_retraction: int = 3, num_gap: int = 3, char: str = ' '):
        super().print_info(num_retraction, num_gap, char)
        ret = char * num_retraction
        print(f'{ret} Using normalized dataset: {self._normed_evaldata}')
        print('-'*80)

    def _normalize_outputs(self, outputs, scaled_outputs, atom_type, num_atoms):
        """Normalize network outputs.
        
        Args:
            outputs: Network outputs
            scaled_outputs: Whether outputs are scaled
            atom_type: Atom types
            num_atoms: Number of atoms
            
        Returns:
            tuple: (outputs, normed_outputs)
        """
        if scaled_outputs:
            normed_outputs = ()
            if self._loss_fn is not None:
                for i in range(self.num_readouts):
                    normed_outputs += (self.scaleshift[i].normalize(outputs[i], atom_type, num_atoms),)
        else:
            normed_outputs = outputs
            outputs = ()
            for i in range(self.num_readouts):
                outputs += (self.scaleshift[i](normed_outputs[i], atom_type, num_atoms),)

        return outputs, normed_outputs

    def forward(self, *inputs):
        """calculate loss function

        Args:
            *input: Tuple of Tensor

        Returns:
            loss (Tensor):  Tensor of shape (B, 1). Data type is float.

        """
        inputs = inputs + (None,)

        atom_type = inputs[self.atom_type_id]
        coordinate = inputs[self.coordinate_id]
        pbc_box = inputs[self.pbc_box_id]
        bonds = inputs[self.bonds_id]
        bond_mask = inputs[self.bond_mask_id]

        labels = tuple(inputs[self.labels_id[i]] for i in range(self.num_labels))

        if atom_type is None:
            atom_type = self.atom_type
        atom_mask = atom_type > 0
        num_atoms = torch.count_nonzero(atom_mask.to(torch.int32), dim=-1).unsqueeze(-1)

        # 处理标签的归一化
        normed_labels = None
        if self._normed_evaldata:
            normed_labels = labels
            labels = ()
            for i in range(self.num_readouts):
                labels += (self.scaleshift[i](normed_labels[i], atom_type, num_atoms),)
            if self.calc_force:
                labels += (self.scaleshift[0].scale_force(normed_labels[-1]),)
        elif self._loss_fn is not None:
            normed_labels = ()
            for i in range(self.num_readouts):
                normed_labels += (self.scaleshift[i].normalize(labels[i], atom_type, num_atoms),)
            if self.calc_force:
                normed_labels += (self.scaleshift[0].normalize_force(labels[-1]),)

        if not self.calc_force:
            # 只计算能量的分支
            outputs = self._network(
                coordinate=coordinate,
                atom_type=atom_type,
                pbc_box=pbc_box,
                bonds=bonds,
                bond_mask=bond_mask,
            )
            if self.num_readouts == 1:
                outputs = (outputs,)
            outputs, normed_outputs = self._normalize_outputs(outputs, self.scaled_outputs, atom_type, num_atoms)
        else:
            with torch.enable_grad():
                # 计算能量和力的分支
                coordinate.requires_grad = True
                outputs = self._network(
                    coordinate=coordinate,
                    atom_type=atom_type,
                    pbc_box=pbc_box,
                    bonds=bonds,
                    bond_mask=bond_mask,
                )
                if self.num_readouts == 1:
                    outputs = (outputs,)
                outputs, normed_outputs = self._normalize_outputs(outputs, self.scaled_outputs, atom_type, num_atoms)
                
                # 计算力
                force = -1 * torch.autograd.grad(
                    outputs[0].sum(),
                    coordinate,
                )[0]

            if self.scaled_outputs:
                normed_force = None
                if self._loss_fn is not None:
                    normed_force = self.scaleshift[0].normalize_force(force)
            else:
                normed_force = force
                force = self.scaleshift[0].scale_force(normed_force)

            if self.num_labels == 1:
                outputs = (force,)
                normed_outputs = (normed_force,)
            else:
                outputs += (force,)
                normed_outputs += (normed_force,)

        # 计算损失
        if self._loss_fn is None:
            loss = self.zero
        else:
            loss = 0
            for i in range(self.num_labels):
                if self._molecular_loss[i]:
                    loss_ = self._loss_fn[i](normed_outputs[i], normed_labels[i], num_atoms, atom_mask)
                else:
                    loss_ = self._loss_fn[i](normed_outputs[i], normed_labels[i])
                loss = loss + loss_ * self._loss_weights[i]

        return loss, outputs, labels, atom_mask
